/**
 * @author 太阳当空丶赵
 * @date 2022/11/30-20:34
 * @version 1.0.0
 * file
 */

const express = require("express")
const fs = require("fs")

const uploadFile = require("../wx/uploadFile")
const getUrl = require("../wx/getDownloadUrl")
const upload = require("../middlewore/multerMiddleware")
const BaseResult = require("../utils/result/BaseResult")
const {wx} = require('../config')
const axios = require('axios')

const fileRouter = express.Router()

fileRouter.post("/uploadImage", upload.single("file"), async (req, res) => {
    try {
        const {filename, path} = req.file
        const result = await uploadFile(path, `images/${filename}`)
        if (result) {
            /*上传成功删除图片*/
            console.log(result)
            fs.unlink(path, () => {})
            /*获取图片下载链接*/
            console.log("path remove", path)
            const imageData = await getUrl(result)
            return res.send(BaseResult.success(imageData))
        }
        return res.send(BaseResult.error())
    } catch (e) {
        console.log(e)
        return res.send(BaseResult.error())
    }
})

fileRouter.get("/uploadTest", async (req, res) => {
    const getUploadPath = `http://api.weixin.qq.com/tcb/uploadfile` // 请求图片上传地址

    const data = {
        "env": wx.EnvId,
        "path": "image/1.jpg"
    }
    try {
        const result = await axios.post(getUploadPath, data)
        return res.send(BaseResult.success(result.data))
    }catch (e){
        return res.send(BaseResult.error(e))
    }

})
fileRouter.get("/downloadTest", async (req, res) => {
    const {cloudPath} = req.query
    console.log(cloudPath)
    const getUrl = `http://api.weixin.qq.com/tcb/batchdownloadfile` // 云调用
    const data = {
        "env": wx.EnvId,
        "file_list": [
            {
                "fileid": cloudPath,
                "max_age":7200
            }
        ]
    }
    try {
        const result = await axios.post(getUrl,data)
        console.info("get download url",data['download_url'])
        return res.send(BaseResult.success(result.data))
    }catch (e) {
        console.info("download err",err)
        return res.send(BaseResult.error(e))
    }
    //     .then(result => {
    //     const data = result.data.file_list[0]
    //     console.info("get download url",data['download_url'])
    //     resolve(data['download_url'])
    // }).catch(err => {
    //     console.info("download err",err)
    //     reject(false)
    // })

})

module.exports = fileRouter
